<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 订单ajax类
 * @package  ajax/backend/bill
 * @author   allen.qiang
 */

quanli_require('module/base/bill/billEdit.class.php');

class ajax_bill {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && quanli_is_int($_REQUEST['operFlg'])) {

            switch($_REQUEST['operFlg']) {

                case 1: //新增或修改订单
                    $this->submitBill();
                    break;
                    
                case 2: //添加订单内部留言
                	$this->addBillInnerWord();
                	break;

                case 3: //审核订单
                    $this->auditBill();
                    break;

                case 4://订单取消
                    $this->cancelBill();
                    break;

                case 5: //人工审核订单在线支付
                    $this->auditBillPay();
                    break;
                case 6://验证现金卡
                    $this->r_checkCard();
                    break;
                case 7://使用现金卡
                    $this->useCard();
                    break;
                case 8://修改运费
                    $this->upfeePaid();
                    break;

                case 9: //澳粒订单下车操作
                    $this->AL_execOutBus();
                    break;

                default:
                    returnJsonData('参数错误');
                    break;

            }
            
        } else {

            returnJsonData('参数错误');

        }
        
    }


    //使用现金卡
    private function useCard()
    {
        global $G_SHOP;
        $bill_no =  $_REQUEST['bill_no'];
        $card_pwd = $_REQUEST['card_pwd'];
        $result = $this->checkCard($_REQUEST['bill_no'],$_REQUEST['card_pwd']);

        quanli_require('module/base/customer/logHandler.class.php');
        //实例日志类
        $logHandler = new logHandler( $G_SHOP->DBCA );

        $log_msg = "";



        if($result['code']==200)
        {

            $G_SHOP->DBCA->beginTransaction();
            try
            {




                $deducation = 0;//代金卡抵扣金额，需计算
                $old_bill_receivable_money = 0;//原应收


                $old_card_amount = 0;//原现金卡抵扣金额
                $old_other_pay_amout = 0;//原其它支付方式应付金额







                //加载类文件
                quanli_include('module/base/promotion/quanliCard.class.php');
                //实例化现金卡类
                $quanliCard = new quanliCard( $G_SHOP->DBCA );
                //查询现金卡信息
                $arg_array = array(
                    'card_pwd' => $card_pwd
                );
                $card_array = $quanliCard->searchCardDetail( $arg_array );



                //error_log(print_r($card_array,1));

                $bill_master = new entity('bill_master');
                $bill_master->bill_no = $bill_no;

                $G_SHOP->DBCA->fetch($bill_master);

                $old_bill_receivable_money = $bill_master->bill_receivable_money;

                if($bill_master->bill_receivable_money - $bill_master->deliver_feePaid <= 0)
                {
                    throw new Exception('没有可抵扣的金额,验证现金卡失败!', 404);
                }



                //应收-运费-代金卡
                $temp_amount = $bill_master->bill_receivable_money - $bill_master->deliver_feePaid - $card_array[0]['face_value'];

                //计算应收
                if($temp_amount>=0)
                {
                    $deducation =  $card_array[0]['face_value'];
                    $bill_master->bill_receivable_money = $bill_master->bill_receivable_money -  $card_array[0]['face_value'];
                }
                else
                {
                    $deducation = $card_array[0]['face_value']  + $temp_amount;
                    $bill_master->bill_receivable_money = $bill_master->deliver_feePaid;
                }

                $bill_master->bill_received_money = $bill_master->bill_received_money + $deducation;//实收金额

                if($bill_master->bill_receivable_money==0)//付款状态:0未付款;1全付;2部分付
                {
                    $bill_master->pay_status = 1;
                }
                else
                {
                    $bill_master->pay_status = 2;
                }

                $bill_master->pay_id_str = $bill_master->pay_id_str.",5";
                $bill_master->pay_name_str = $bill_master->pay_id_str.",代金卡";


                //订单支付表
                $bill_pay = new entity('bill_pay');
                $bill_pay->bill_no = $bill_no;
                $bill_pay->payTypeID = 5;
                $G_SHOP->DBCA->fetch($bill_pay);
                if($bill_pay)
                {

                    $old_card_amount = $bill_pay->pay_amount;//原现金卡抵扣金额

                    $bill_pay->creator = $G_SHOP->currentUserID;
                    $bill_pay->pay_amount += $deducation;
                    $bill_pay->deduct_amount += $deducation;
                    $bill_pay->payTypeName = "代金卡";
                    $bill_pay->type = 7;
                    $bill_pay->paid_confirm_status = 0;
                    $bill_pay->receipt_amount = 0;
                    $bill_pay->is_waste = 0;


                }
                else
                {
                    $bill_pay->creator = $G_SHOP->currentUserID;
                    $bill_pay->payTypeName = "代金卡";
                    $bill_pay->type = 7;
                    $bill_pay->pay_amount = $deducation;
                    $bill_pay->deduct_amount = $deducation;
                    $bill_pay->paid_confirm_status = 0;
                    $bill_pay->receipt_amount = 0;
                    $bill_pay->is_waste = 0;
                }
                $G_SHOP->DBCA->save($bill_pay);




                //订单使用代金卡表
                $bill_use_card_obj = new entity('bill_use_card');
                $bill_use_card_obj->creator = $card_array[0]['creator'];
                $bill_use_card_obj->bill_no = $bill_master->bill_no;
                $bill_use_card_obj->bill_code = $bill_master->bill_code;
                $bill_use_card_obj->card_no = $card_array[0]['card_no'];
                $bill_use_card_obj->card_pwd = encryptD($card_array[0]['card_pwd']) ;
                $bill_use_card_obj->card_name = $card_array[0]['card_name'];
                $bill_use_card_obj->face_value = $card_array[0]['face_value'];
                $bill_use_card_obj->isUse = 1;
                $bill_use_card_obj->deduction = $deducation;


                //更新代金卡状态
                $card_sql = 'UPDATE card_detail SET used_number=used_number+1, card_status=6, bill_no = ? WHERE card_no = ? AND card_pwd = ? AND card_status = 5 AND used_number < can_use_number';
                $card_result = $G_SHOP->DBCA->stmt_query($card_sql, 'sss', $bill_no, $bill_use_card_obj->card_no, $bill_use_card_obj->card_pwd);
                if(!$card_result){
                    throw new Exception('代金卡使用失败2', 404);/////
                }

                $G_SHOP->DBCA->save($bill_use_card_obj);




                //其它支付方式减去相应的金额

                $other_pay_array = $G_SHOP->DBCA->stmt_query('SELECT * FROM bill_pay WHERE bill_no = ? AND payTypeID!=5 AND is_waste = 0 ORDER BY type ASC LIMIT 1','s',$bill_no);
                $other_apy = $other_pay_array[0];
                $old_other_pay_amout = $other_apy->pay_amount;
                $pay_amount = $other_apy->pay_amount - $deducation;


                $other_pay_update_result = $G_SHOP->DBCA->stmt_query('UPDATE bill_pay set pay_amount = ? WHERE uuid = ? ','ds', array($pay_amount, $other_apy->uuid));
                if(!$other_pay_update_result){
                    throw new Exception('代金卡使用失败1', 404);//
                }



                $bill_master->bill_card_money = $bill_pay->deduct_amount;//代金卡抵扣金额

                $G_SHOP->DBCA->save($bill_master);






                //记录日志

                $log_msg .= '现金卡号：'.$bill_use_card_obj->card_no;
                $log_msg .= '<br />面值：'.$bill_use_card_obj->face_value;
                $log_msg .= '<br />抵扣金额：'.$bill_use_card_obj->deduction;
                $log_msg .= '<br />总现金卡抵扣金额：' . $old_card_amount . '->' . $bill_pay->deduct_amount;
                $log_msg .= '<br />订单应收：' . $old_bill_receivable_money . '->' . $bill_master->bill_receivable_money;
                $log_msg .= '<br />'.$other_apy->payTypeName.'：'.$old_other_pay_amout .'->' . $pay_amount;


                $log = array(
                    //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                    //'operator'=> $G_SHOP->currentUserID,
                    'operator' => $G_SHOP->currentUserName,
                    //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
                    'logItem'=>$bill_no,
                    'logCategoryID'=>1,
                    'extend_1'=>'验证现金卡',
                    'extend_2'=>$log_msg,
                    'extend_5'=>$bill_master->bill_status


                );

                //保存订单日志
                $logHandler->saveLogInfo( $log );

                $G_SHOP->DBCA->commit();

                returnJsonData('验证成功',200);
            }
            catch(Exception $e)
            {
                $G_SHOP->DBCA->rollBack();
                returnJsonData($e->getMessage(),400);
            }




            //returnJsonData($result['message'],$result['code'],$result['data']);
        }
        else
        {
            //returnJsonData($result['message'],$result['code']);
        }

        returnJsonData($result['message'],$result['code']);
    }


    /**
     * 验证现金卡
     */
    private function r_checkCard() {

        $result = $this->checkCard($_REQUEST['bill_no'],$_REQUEST['card_pwd']);

        if($result['code']==200)
        {
            returnJsonData($result['message'],$result['code'],$result['data']);
        }
        else
        {
            returnJsonData($result['message'],$result['code']);
        }


    }


    //验证现金卡
    private function checkCard($bill_no,$card_pwd)
    {

        global $G_SHOP;

        if (!isset($bill_no) || empty($bill_no)) {
            returnJsonData('订单号不存在');
        }

        if (!isset($card_pwd) || empty($card_pwd)) {
            returnJsonData('请输入卡密码');
        }



        //加载类文件
        quanli_require('module/base/bill/billSearch.class.php');
        quanli_require('module/base/customer/quanliCust.class.php');
        quanli_require('module/base/customer/custDeliver.class.php');
        quanli_require('module/base/goods/quanliGoods.class.php');
        quanli_require('module/base/goods/goodsFittings.class.php');
        quanli_require('module/base/system/itemHandler.class.php');
        quanli_require('module/base/promotion/quanliCoupon.class.php');
        quanli_require('module/func/eai.func.php');

        //实例订单类
        $billSearch = new billSearch();
        //实例item类
        $itemHandler = new itemHandler();
        //实例会员类
        $quanliCust = new quanliCust();
        //实例会员地址类
        $custDeliver = new custDeliver();
        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();
        //实例商品类
        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );
        //实例商品配件类
        $goodsFittings = new goodsFittings( $G_SHOP->DBCA );
        //实例化ebsig接口操作类
        $ebsigEai = eai_crm();


        //查询订单信息
        $args_array = array(
            'bill_no' => $bill_no
        );
        $bill_array = $billSearch->searchBillInfo( $args_array );


        if (!$bill_array) {
            backendError('订单信息没有找到');
        }
        if ( ! in_array($bill_array[0]['bill_status'], array( 5, 6))) {
            backendError('该订单状态无法验证现金卡');
        }


        $bill_array = $bill_array[0];
        $pcustID = $bill_array['pcustID'];


        $billType = $bill_array['billType'];



        /**
         * ==================
         * 检查当前订单使用的收货地址是否和现在的收货地址相同，如果不同，则新增收货地址
         * ==================
         */
//        $deliver_array = $custDeliver->searchCustDeliverDetail( $bill_array['deliverid'], $pcustID );
//        $has_new_add = 0;
//        if (!$deliver_array) {
//            $has_new_add = 1;
//        } else {
//            $new_deliver = $deliver_array['provinceName'] . $deliver_array['cityName'] . $deliver_array['countyName'] . $deliver_array['address']
//                . $deliver_array['custName'] . $deliver_array['mobile'] . $deliver_array['phone'];
//            $old_deliver = $bill_array['deliver_province'] . $bill_array['deliver_city'] . $bill_array['deliver_county'] . $bill_array['deliver_address']
//                . $bill_array['deliver_name'] . $bill_array['deliver_mobile'] . $bill_array['deliver_phone'];
//            if ($new_deliver != $old_deliver) {
//                $has_new_add = 1;
//            }
//        }
//        if ($has_new_add) {
//
//            $deliver_args_array = array(
//                'creator' => 'system',
//                'pcustID' => $pcustID,
//                'provinceid' => $bill_array['deliver_provinceid'],
//                'cityid' => $bill_array['deliver_cityid'],
//                'countyid' => $bill_array['deliver_countyid'],
//                'address' => $bill_array['deliver_address'],
//                'custName' => $bill_array['deliver_name'],
//                'mobile' => $bill_array['deliver_mobile'],
//                'phone' => $bill_array['deliver_phone'],
//            );
//            $result_array = $custDeliver->editCustDeliver( $deliver_args_array );
//            if ($result_array['code'] != 200) {
//                backendError('新增收货地址：'. $result_array['message']);
//            }
//            $bill_array['deliverid'] = $result_array['data']['deliverID'];
//
//        }


        //查询当前订单是否已被代付
        $bill_paying_agent_array = $billSearch->searchBillPayingAgent( array( 'bill_no' => $bill_no ) );
        if ($bill_paying_agent_array) {
            backendError('订单被其他订单代付，无法修改');
        }


        //查询订单优惠券
        //$bill_coupon_array = $billSearch->searchBillUsedCoupon( $bill_no );


        //查询订单代金卡
        $bill_card_array = $billSearch->searchBillUsedCard( $bill_no );


        //查询代付订单
        //$bill_paying_agent_array = $billSearch->searchBillPayingAgent( array( 'main_bill_no' => $_REQUEST['bill_no'] ) );


        //查询订单商品信息
        $bill_goods_array = $billSearch->searchBillGoods( $args_array );
        $cart_goods_array = array();
        $index = 1;
        foreach ($bill_goods_array as &$bill_goods) {

            //查询订单商品配件
            $args_array = array(
                'bill_goods_no' => $bill_goods['bill_goods_no']
            );
            $bill_goods_fittings_array = $billSearch->searchGoodsFittingsBill( $args_array );

            //查询商品信息
            $args_array = array(
                'postID' => $bill_goods['goods_postID']
            );
            $goods_array = $quanliGoods->searchGoodsSaleDetail($args_array);

            //查询商品配件
            $goods_fittings_array = $goodsFittings->searchGoodsFitsRelation( $args_array );
            if ($goods_fittings_array) {
                foreach($goods_fittings_array as &$goods_fittings) {
                    if ($goods_fittings['forsale'] == 0) {
                        continue;
                    } else if (!isset($bill_goods_fittings_array[$goods_fittings['fitID']])) {
                        continue;
                    }
                    $goods_fittings['buyNum'] = $bill_goods_fittings_array[$goods_fittings['fitID']]['buyNum'];
                }
            }

            $cart_goods_array[$index] = array (
                'bill_goods_no' => $bill_goods['bill_goods_no'],
                'goodsID' => $goods_array['goodsID'],
                'postID' => $goods_array['postID'],
                'cityID' => $goods_array['cityID'],
                'goodsName' => $goods_array['goodsName'],
                'spec' => $goods_array['spec'],
                'goods_amount' => 1,
                'salePrice' => $goods_array['salePrice'],
                'price' => $bill_goods['goods_purchasePrice'],
                'goods_remark' => $bill_goods['goods_remark'],
                'birthday_card' => $bill_goods['birthday_card'],
                'segmentation' => $bill_goods['segmentation'],
                'salePoints' => 0,
                'goodsWeight' => 0,
                'goods_from' => 1,
                'goods_groupID' => 0,
                'goods_status' => 1,
                'goodsMainPic' => $goods_array['goodsMainPic'],
                'bigCategoryID' => $goods_array['bigCategoryID'],
                'midCategoryID' => $goods_array['midCategoryID'],
                'smallCategoryID' => $goods_array['smallCategoryID'],
                'product_code' => $goods_array['product_code'],
                'syncopate' => explode('|', $goods_array['syncopate']),
                'birthcard' => explode('|', $goods_array['birthcard']),
                'twoPostID' => $goods_array['twoPostID'],
                'marketPrice' => $goods_array['marketPrice'],
                'startDeliver' => $goods_array['startDeliver'],
                'endDeliver' => $goods_array['endDeliver'],
                'deliverSpace' => $goods_array['deliverSpace'],
                'cutTime' => $goods_array['cutTime'],
                'goods_weight' => 0,
                'fittings' => $goods_fittings_array,
                'fittings_json' => json_encode($goods_fittings_array),
                'adjustPrice' => $bill_goods['auth_alter'] ? $bill_goods['goods_purchasePrice'] : -1,
                'promotion' => null
            );

            ++$index;

        }


        if (!isset($cart_goods_array) || empty($cart_goods_array)) {
            returnJsonData('请先添加商品');
        }

        $use_card_array = array(
            'balance' => 0,
            'detail' => array()
        );

//        foreach($bill_card_array as $card)
//        {
//            $use_card_array['use_card']['detail'][$card['card_pwd']]=$card['card_pwd'];
//
//        }

        //加载类文件
        quanli_include('module/base/promotion/quanliCard.class.php');
        //实例化现金卡类
        $quanliCard = new quanliCard( $G_SHOP->DBCA );
        //验证是否已经使用
        $result_array = $quanliCard->checkCard( $card_pwd, $cart_goods_array, $use_card_array, $bill_no );
        if ($result_array['code'] == 200) {

            //查询现金卡信息
            $arg_array = array(
                'card_pwd' => $card_pwd
            );
            $card_array = $quanliCard->searchCardDetail( $arg_array );

            if($card_array[0]['card_status'] == 6)
            {
                return array('code'=>400,'message'=>'代金卡已被使用!');
            }

            $result_array['data']=$card_array;
            return $result_array;
        } else {
            return $result_array;

        }

    }





    /**
     * 人工审核订单在线支付
     */
    private function auditBillPay() {

        global $G_SHOP;

        //实例订单类
        $billEdit = new billEdit( $G_SHOP->DBCA );

        //人工审核订单在线支付
        $_REQUEST['operator'] = $G_SHOP->currentUserID;
        $result_array = $billEdit->auditBillPay( $_REQUEST );

        echo json_encode( $result_array );

    }

    /**
     * 提交订单
     */
    private function submitBill() {

        global $G_PGLOB;

        //加载类文件
        quanli_include('module/base/common/quanliHttp.class.php');
        quanli_include('module/base/system/itemHandler.class.php');
        quanli_include('module/base/company/companyMaster.class.php');

        //实例http类
        $quanliHttp = new quanliHttp();

        //实例化大客户类
        $companyMaster = new companyMaster();

        $bill_array = $G_PGLOB->sessionCache_get('checkout_backend_' . $_REQUEST['orders_code'], true);

        if (!isset($_REQUEST['pcustID'], $_REQUEST['invoice_content']) || !is_numeric($_REQUEST['pcustID']) ) {
            returnJsonData('参数错误');
        }

        if(!isset($_REQUEST['urgent']) || !is_numeric($_REQUEST['urgent'])){
            returnJsonData('请选择单据标识');
        }

        if(!isset($_REQUEST['billPlatform']) || !is_numeric($_REQUEST['billPlatform'])){
            returnJsonData('请选择订单平台');
        }

        if (!isset($_REQUEST['billChannel']) || !in_array($_REQUEST['billChannel'], array(1, 2, 3, 4, 5, 6))) {
            returnJsonData('请选择订单渠道');
        }

        if (!isset($_REQUEST['billType']) || !in_array($_REQUEST['billType'], array(1, 2, 3, 4, 5, 6,7,8,9))) {
            returnJsonData('请选择订单类型');
        }

        //试吃订单
        if(isset($bill_array['master']['foretaste']) && $bill_array['master']['foretaste'] == 1){
            $arg_array = array(
                'pcustID' => $_REQUEST['pcustID']
            );
            $companyMaster_array = $companyMaster->search($arg_array);

            if(!$companyMaster_array){
                returnJsonData('该会员不是大客户，不能试吃');
            }
        }

        //城市
        if(!isset($bill_array['master']['cityid']) || !is_numeric($bill_array['master']['cityid'])){
            returnJsonData('请选择城市');
        }

        //促销渠道
        if(!isset($bill_array['master']['billPromotion']) || !is_numeric($bill_array['master']['billPromotion'])){
            returnJsonData('请选择促销渠道');
        }

        //检查收货地址
        if (!isset($bill_array['master']['deliverid']) || empty($bill_array['master']['deliverid'])) {
            returnJsonData('请选择收货地址');
        }

        //检查配送方式
        if (!isset($bill_array['master']['sendTypeID']) || empty($bill_array['master']['sendTypeID'])) {
            returnJsonData('请选择配送方式');
        }
        //试吃订单默认支付方式 货到付款——现金
        if($_REQUEST['billType']==9){
            $bill_array['master']['pay_type']=1;
            $bill_array['master']['payTypeID']=1;
            $bill_array['master']['payment_method_id']=58;
        }

        //检查支付方式
        if (!isset($bill_array['master']['payTypeID']) || empty($bill_array['master']['payTypeID'])) {
            returnJsonData('请选择支付方式');
        }

        if ($bill_array['master']['payTypeID'] == 1) {
            if(!isset($bill_array['master']['payment_method_id'])){
                returnJsonData('请选择付款方式');
            }
        } else {
            $bill_master_array['payment_method_id'] = null;
            $bill_master_array['payment_method_name'] = null;
            $bill_master_array['payment_method_type'] = null;
        }

        //普通商品
        if(isset($bill_array['goods']['general']) && !empty($bill_array['goods']['general'])){
            foreach($_REQUEST['general_goods'] as $key=>$v) {
                $bill_array['goods']['general'][$key]['birthday_card'] = $v['birthcard'];       //生日牌
                $bill_array['goods']['general'][$key]['segmentation'] = $v['syncopate'];        //切分
                $bill_array['goods']['general'][$key]['productRemark'] = $v['productRemark'];  //生产备注
            }
        }


        $card_is_invoice = 1;   //默认是可以开发票

        //付现方式
        if (isset($bill_array['master']['pay_type']) && $bill_array['master']['pay_type'] == 1) {

            if (!isset($bill_array['master']['payment_method_id']) || !is_numeric($bill_array['master']['payment_method_id'])) {
                returnJsonData('请选择付现方式');
            }

            if(isset($bill_array['master']['card_is_invoice']) && $bill_array['master']['card_is_invoice'] == 0)
                $card_is_invoice = 0;

        } else {
            $bill_array['master']['payment_method_id'] = 0;
            $bill_array['master']['payment_method_name'] = null;
            $bill_array['master']['payment_method_type'] = 0;
        }

        //实例化字典类
        $itemHandler = new itemHandler();

        if(!isset($bill_array['master']['invoice'])){
            returnJsonData('请选择发票');
        }

        //=======================================
        //=========发票内容======================
        //=======================================
        if (isset($bill_array['master']['invoice']) && $bill_array['master']['invoice'] == 1 && $card_is_invoice == 1) {         //开发票

            if (!isset($_REQUEST['invoice_content'],$_REQUEST['invoice_content_id'])) {
                returnJsonData('请选择发票内容');
            }

            if(empty($_REQUEST['invoice_content']) || empty($_REQUEST['invoice_content_id'])){
                returnJsonData('发票内容不能为空');
            }

            $item_array = array(
                'itemCategoryID' => 12,
                'itemID' => $_REQUEST['invoice_content_id'],
                'useFlg' => 1
            );
            $invoice_content_array = $itemHandler->searchItem( $item_array );

            if (!$invoice_content_array) {
                returnJsonData('发票内容错误');
            }

            $bill_array['master']['invoice_content_id'] = $invoice_content_array[0]['itemID'];
            $bill_array['master']['invoice_content'] = $invoice_content_array[0]['itemName'];

        } else {    //不开发票
            $bill_array['master']['invoice'] = 0;
            $bill_array['master']['invoiceID'] = 0;
            $bill_array['master']['invoice_content_id'] = null;
            $bill_array['master']['invoice_content'] = null;
        }

        //内部留言
        if (isset($_REQUEST['bill_remark']) && !empty($_REQUEST['bill_remark'])) {
            $bill_array['remark'] = $_REQUEST['bill_remark'];
        }

        //add allen.qiang 20141030 农业银行信用卡五折购 start
        quanli_require('module/base/activity/activitySpike.class.php');
        $activityspike=new activitySpike();
        if($bill_array['master']['billPromotion'] == $activityspike->billPromotion_ny_xyk){
            //是否含有一磅蛋糕
            $isbool=false;
            $general=$bill_array['goods']['general'];
            foreach($general as &$goods){
                if($goods['spec']=="1磅" && $goods['goodsName']!="悦时光")
                    $isbool=true;
            }
            //使用优惠券
            $use_coupon = 0;
            if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
                $use_coupon = 1;
            }
     
            if(($bill_array['master']['payTypeID']==$activityspike->payTypeID_ny_xyk || $bill_array['master']['payment_method_id']==$activityspike->paymentID_ny_xyk) && $bill_array['master']['cityid']==110 && $activityspike->nh_xyk_isDate() && $isbool && $activityspike->nh_xyk_num400()>0){ //判断是否是用农业银行信用卡支付且在活动时间内并且是上海站的1磅蛋糕
                if($bill_array['use_points']['bill_points_money']>0 || $use_coupon==1 || (isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail']))){ //农业银行信用卡五折购不能享受现金卡、专享卡、优惠券、红包、积分、会员等级制度
                    $bill_array['master']['billPromotion']=0;
                }
            }else{
                $bill_array['master']['billPromotion']=0;
            }
        }
        //add allen.qiang 20141030 农业银行信用卡五折购 end

        //=======================================
        //=========订单备注======================
        //=======================================
        if (!isset($_REQUEST['remark']) || empty($_REQUEST['remark'])) {
            $bill_array['master']['remark'] = null;
        } else {
            $bill_array['master']['remark'] = $_REQUEST['remark'];
        }


        //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---start
        quanli_require('module/base/activity/activityCbc.class.php');
        //实例建设银行五折购活动类
        $activityCBC=new activityCbc();
        $activity_master=$activityCBC->activity_master($_REQUEST);
        if($bill_array['master']['billPromotion'] == $activity_master["billPromotion"]){ //选择了建行信用卡五折购促销
            if($bill_array['master']['payment_method_id']==$activity_master["paymentID_CBC"] && !(isset($_REQUEST['bill_no']) && !empty($_REQUEST['bill_no']))) {//选择了货到刷建行信用卡且不是修改订单
                if($activity_master["isDate"]!=1){ //判断是否是活动时间内
                    returnJsonData('今天不是建行信用卡五折购活动时间');
                }

                if($activity_master["activity_num"]<=0){ //判断当日建行信用卡活动蛋糕数量
                    returnJsonData('今天建行信用卡五折购活动蛋糕已售罄！');
                }

                if($activity_master["activity_status"]==1){ //判断用户是否当日已经购买过建行信用卡五折购蛋糕
                    returnJsonData('该用户今日已购买过建设银行信用卡五折购蛋糕！');
                }

                if (!isset($_REQUEST['remark']) || empty($_REQUEST['remark']) ||!strstr(strtolower($_REQUEST['remark']),"ccb")) { //判断是否输入了建行信用卡配送备注
                    returnJsonData('请输入配送备注（CCB+建设银行信用卡卡号后四位，例：CCB7822）');
                }

                //是否含有一磅蛋糕
                $isbool=false;
                $general=$bill_array['goods']['general'];
                foreach($general as &$goods){
                    if($goods['spec']=="1磅" && $goods['goodsName']!="悦时光")
                        $isbool=true;
                }
                //使用优惠券
                $use_coupon = 0;
                if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
                    $use_coupon = 1;
                }
                if($bill_array['master']['payment_method_id']==$activity_master["paymentID_CBC"] && $bill_array['master']['cityid']==110 && $activity_master["isDate"]==1 && $isbool && $activity_master["activity_num"]>0){ //判断是否是用建行信用卡支付且在活动时间内并且是上海站的1磅蛋糕
                    if($bill_array['use_points']['bill_points_money']>0 || $use_coupon==1 || (isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail']))){ //建行信用卡五折购不能享受现金卡、专享卡、优惠券、红包、积分
                        $bill_array['master']['billPromotion']=0;
                    }
                }else{
                    $bill_array['master']['billPromotion']=0;
                }

            }

        }
        //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---end


        //验证
        $is_auth = $G_PGLOB->sessionCache_get( 'AUTH_' . $_REQUEST['code'], true );
        if ($is_auth) {
            $bill_array['master']['auth_alter'] = 1;
        } else {
            $bill_array['master']['auth_alter'] = 0;
        }

        //订单标识
        $bill_array['master']['urgent'] = $_REQUEST['urgent'];


        //特殊状态
        if($_REQUEST['billType'] == 8)
            $bill_array['master']['special_status'] = 4;


        //实例订单类
        $billEdit = new billEdit( $G_PGLOB->DBCA );                     //实例订单编辑类

        $bill_array['pcustID'] = $_REQUEST['pcustID'];

        $bill_array['master']['numPeo'] = (isset($_REQUEST['numPeo']) && !empty($_REQUEST['numPeo'])) ? $_REQUEST['numPeo'] : 0;//试吃人数

        if (isset($_REQUEST['bill_no']) && !empty($_REQUEST['bill_no'])) {  //修改
            $bill_array['master']['billType'] = $_REQUEST['billType'];
            $bill_array['bill_no'] = $_REQUEST['bill_no'];
            $result_array = $billEdit->createAlterBillData( $bill_array, $G_PGLOB->currentUserName );

        } else {    //新增

            $bill_array['master']['billPlatform'] = $_REQUEST['billPlatform'];
            $bill_array['master']['billChannel'] = $_REQUEST['billChannel'];
            $bill_array['master']['billType'] = $_REQUEST['billType'];
            //error_log(print_r( $_REQUEST['billType'],1));
			//add yim.hu 20141201 FUN-BK-0033 新增订单前CHECK --start
			//首先判断是否需要检查一下数据是否重复
            
			if($_REQUEST['check_result']==1){
			
				$check_result = $billEdit->check_bill($bill_array);
                //mod allen.qiang 20141218 FUN-BK-0033 新增订单前CHECK --start
                if($check_result==1){
                    returnJsonData('',200);
                }else{
                    returnJsonData($check_result,555);
                }
                //mod allen.qiang 20141218 FUN-BK-0033 新增订单前CHECK --end
				//echo $check_result;
				return false;
			}
			
            //add yim.hu 20141201 FUN-BK-0033 新增订单前CHECK --end
			
            $result_array = $billEdit->creareBillData( $bill_array, $G_PGLOB->currentUserName );

        }


        //判断返回数据
        if ($result_array['code'] == 200) {

            $bill_index = $bill_array['bill_no'] . $_REQUEST['pcustID'];

            //保存订单信息到redis

            $G_PGLOB->sessionCache_set('bill_' . $bill_index, $bill_array, 0, true);

 
            $request_result_array = $quanliHttp->get( G_LAN_DAMAIN . '/app_thread_async/billEdit.php?bill_index=' . $bill_index );

            $G_PGLOB->sessionCache_remove('bill_' . $bill_index, true);

            if ($request_result_array['code'] == 200 && $request_result_array['data']['code'] == 200) {

//
                if(isset($companyMaster_array) && !empty($companyMaster_array))
                {
                    if($companyMaster_array[0]['properties']==2)
                    {
//                        $args_array = array(
//                            'bill_no' => $bill_array['bill_no'],
//                            'creator' => $G_PGLOB->currentUserID
//                        );

                        //$billEdit->auditBill( $args_array, false );
                    }

                }
                else if ($_REQUEST['bill_no'] == ''  ) {
                        $args_array = array(
                            'bill_no' => $bill_array['bill_no'],
                            'creator' => $G_PGLOB->currentUserID
                        );

                        $billEdit->auditBill( $args_array, false );
                    }
                //add by 20141105 allen.qiang FUN-AC-0013-销售BD双11活动 start
                $this->activities($result_array);
                //add by 20141105 allen.qiang FUN-AC-0013-销售BD双11活动 end

                returnJsonData($result_array['message'], $result_array['code'], $result_array['data']);






            } else {

                returnJsonData($request_result_array['data']['message'], $request_result_array['data']['code']);

            }

        } else {
            returnJsonData($result_array['message'], $result_array['code']);
        }

    }


    /**
     * 取消订单
     */
    private function cancelBill() {

        global $G_PGLOB;

        //实例订单类
        $billEdit = new billEdit( $G_PGLOB->DBCA );

        //操作人
        $operator = $G_PGLOB->currentUserName;


        //取消订单
        $result_array = $billEdit->cancelBill( $_REQUEST['bill_no'], $operator );

        returnJsonData($result_array['message'], $result_array['code']);

    }

    /**
     * 审核订单
     */
    private function auditBill() {


        global $G_PGLOB;

        //实例订单类
        $billEdit = new billEdit( $G_PGLOB->DBCA );

        //审核订单
        $_REQUEST['creator'] = $G_PGLOB->currentUserID;

        $result_array = $billEdit->auditBill( $_REQUEST );

        returnJsonData($result_array['message'], $result_array['code']);

    }

    /**
     * 添加订单内容留言
     */
    private function addBillInnerWord() {

        global  $G_PGLOB;

        //实例化订单内部留言类
        $billEdit = new billEdit( $G_PGLOB->DBCA );
    	//mod by yu.zan 20141127 FUN-BK-0038-订单内部留言操作者显示变更 start
    	//$_REQUEST['creator'] = $G_PGLOB->currentUserID;
        $_REQUEST['creator'] = $G_PGLOB->currentUserName;
        //mod by yu.zan 20141127 FUN-BK-0038-订单内部留言操作者显示变更 end

        //保存内容留言
    	$result_array = $billEdit->saveBillInnerWord( $_REQUEST ) ;

        if($result_array['code'] == 200){

            returnJsonData( $result_array['message'], $result_array['code'], $result_array['data'] );
        }else{
            
            returnJsonData( $result_array['message'], $result_array['code'] );
        }

    }

    /**
     * 修改运费
     */
    private function upfeePaid(){
        global $G_SHOP;
        $bill_no =  $_REQUEST['bill_no'];
        $deliver_feePaid = $_REQUEST['deliver_feePaid'];
        if (!isset($bill_no) || empty($bill_no)) {
            returnJsonData('订单号不存在');
        }

        if (!isset($deliver_feePaid)) {
            returnJsonData('请输入运费金额');
        }
        quanli_require('module/base/customer/logHandler.class.php');
        quanli_require('module/base/bill/billSearch.class.php');
        //实例日志类
        $logHandler = new logHandler( $G_SHOP->DBCA );

        $log_msg = "";

        $G_SHOP->DBCA->beginTransaction();
        try
        {

            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $bill_no;

            $G_SHOP->DBCA->fetch($bill_master);
            $bill_receivable_money=$bill_master->bill_receivable_money;//应收金额
            $bill_deliver_feePaid=$bill_master->deliver_feePaid;//运费
            $bill_money=$bill_master->bill_money;//订单金额

            //实例订单类
            $billSearch = new billSearch( $G_SHOP->DBCA );
            //查询参数
            $arg_array = array(
                'bill_no' => $bill_no,
                'sortname' => 'type',
                'sortorder' => 'asc'
            );

            $pay_amount=0;//修改的支付金额
            $type=1;//支付方式类型
            $typeName="";//支付方式名称
            $pay_amount2=0;//原支付金额

            //订单支付方式
            $bill_pay_array = $billSearch->searchBillPay( $arg_array );
            foreach ($bill_pay_array as $bill) {
                if($bill["type"]==1||$bill["type"]==2){
                    $pay_amount=$bill["pay_amount"];
                    $type=$bill["type"];
                    $typeName=$bill["payTypeName"];
                    $pay_amount2=$bill["pay_amount"];
                }
            }

            if($bill_receivable_money<$bill_deliver_feePaid){
                $G_SHOP->DBCA->commit();
                returnJsonData('此单运费已付款，不能修改运费');
            }else if($deliver_feePaid>0&&$bill_deliver_feePaid>$deliver_feePaid){
                $bill_receivable_money=$bill_receivable_money - ($bill_deliver_feePaid-$deliver_feePaid);
                $bill_money=$bill_money - ($bill_deliver_feePaid-$deliver_feePaid);
                $pay_amount=$pay_amount - ($bill_deliver_feePaid-$deliver_feePaid);
            }else if($deliver_feePaid>0&&$bill_deliver_feePaid<$deliver_feePaid){
                $bill_receivable_money=$bill_receivable_money + ($deliver_feePaid-$bill_deliver_feePaid);
                $bill_money=$bill_money + ($deliver_feePaid-$bill_deliver_feePaid);
                $pay_amount=$pay_amount + ($deliver_feePaid-$bill_deliver_feePaid);
            }else if($deliver_feePaid==0){
                $bill_receivable_money=$bill_receivable_money - $bill_deliver_feePaid;
                $bill_money=$bill_money - $bill_deliver_feePaid;
                $pay_amount=$pay_amount - $bill_deliver_feePaid;
            }

            //修改支付金额
            $bill_pay = new entity('bill_pay');
            $bill_pay->bill_no = $bill_no;
            $bill_pay->type = $type;
            if($G_SHOP->DBCA->fetch($bill_pay)){
                $bill_pay->pay_amount = $pay_amount;
                $G_SHOP->DBCA->save($bill_pay);
            }

            //付款状态
            $pay_status=0;
            if($bill_receivable_money==0){
                $pay_status=1;
            }else if($bill_money>$bill_receivable_money){
                $pay_status=2;
            }

            //记录日志
            $log_msg .= '支付状态：'.$this->ruturnPay_status($bill_master->pay_status). '->' .$this->ruturnPay_status($pay_status);
            $log_msg .= '<br />运费：'.$bill_master->deliver_feePaid. '->' .$deliver_feePaid;
            $log_msg .= '<br />订单金额：' . $bill_master->bill_money . '->' . $bill_money;
            $log_msg .= '<br />应收金额：' . $bill_master->bill_receivable_money . '->' . $bill_receivable_money;
            $log_msg .= '<br />'.$typeName.'：' . $pay_amount2 . '->' . $pay_amount;

            //修改订单金额、应收金额、运费、付款状态
            $bill_master->bill_receivable_money=$bill_receivable_money;
            $bill_master->deliver_feePaid=$deliver_feePaid;
            $bill_master->bill_money=$bill_money;
            $bill_master->pay_status=$pay_status;

            $G_SHOP->DBCA->save($bill_master);

            $log = array(
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                //'operator'=> $G_SHOP->currentUserID,
                'operator' => $G_SHOP->currentUserName,
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
                'logItem'=>$bill_no,
                'logCategoryID'=>1,
                'extend_1'=>'修改运费',
                'extend_2'=>$log_msg,
                'extend_5'=>$bill_master->bill_status


            );

            //保存订单日志
            $logHandler->saveLogInfo( $log );

            $G_SHOP->DBCA->commit();

            returnJsonData('修改运费成功',200);
        }
        catch(Exception $e)
        {
            $G_SHOP->DBCA->rollBack();
            returnJsonData($e->getMessage(),400);
        }
    }

    //根据付款状态ID返回付款状态名称
    public function ruturnPay_status($status){
        switch($status){
            case 0:
                return "未付款";
                break;
            case 1:
                return "全付";
                break;
            default:
                return "部分付";
                break;
        }
    }

    /**
     * 澳粒订单下车操作
     * @author create by allen.qiang
     */
    private function AL_execOutBus(){

        global  $G_PGLOB;

        if(!isset($_REQUEST['bill_no']) || empty($_REQUEST['bill_no'])){
            returnJsonData('缺少参数');
        }

        $bill_no = $_REQUEST['bill_no'];

        try{

            //开启事务
            $G_PGLOB->DBCA->beginTransaction();

            //====================修改订单主表订单信息start======================
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $bill_no;
            if (!$G_PGLOB->DBCA->fetch($bill_master)){
                throw new Exception( '订单信息不存在' , 404 );
            }

            if( $bill_master->bill_status == 0){
                throw new Exception( '订单还未审核确认,请审核确认后再下车' , 400 );
            }
            if( $bill_master->bill_status == 5){
                throw new Exception( '订单已经下车,无需重复下车操作' , 400 );
            }

            //修改订单状态为下车
            $bill_master->bill_status = 5;
            $G_PGLOB->DBCA->save( $bill_master );
            //====================修改订单主表订单信息end======================

            //引用订单信息类
            quanli_require('module/base/bill/billGoodsProduct.class.php');
            //====================修改订单商品表订单信息start======================
            $arg_array = array(
                'bill_no'=>$bill_no
            );
            $bill_goods = new billGoodsProduct();
            $bill_goods_array = $bill_goods->searchBillGoods( $arg_array );
            if( !$bill_goods_array ){
                throw new Exception( '订单商品信息不存在' , 404 );
            }
            foreach ( $bill_goods_array as $val){
                $bill_goods = new entity('bill_goods');
                $bill_goods->bill_no = $val['bill_no'];
                if ( !$G_PGLOB->DBCA->fetch( $bill_goods ) ){
                    throw new Exception( '订单商品信息不存在' , 404 );
                }
                $bill_goods->is_busScan = 1;
                $bill_goods->busScan_operator = $G_PGLOB->currentUserID;
                $bill_goods->busScan_time = $G_PGLOB->sys_datetime;
                $G_PGLOB->DBCA->save( $bill_goods );
            }
            //====================修改订单商品表订单信息end======================


            /*=======================================================
            * 下车写入日志 start
            * ======================================================
            */
            quanli_include('module/base/customer/logHandler.class.php');
            //实例日志类
            $logHandler = new logHandler( $G_PGLOB->DBCA );

            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $bill_no,
                'extend_1' => '配送站已收货',
                'extend_2' => $bill_master->bill_code.' '.'配送站已收货',
                'extend_5' =>5,
                'operator' => $G_PGLOB->currentUserName ? $G_PGLOB->currentUserName : $G_PGLOB->currentUserID
            );

            $result_array = $logHandler->saveLogInfo( $log_array );
            if ($result_array['code'] != 200){
                throw new Exception( $result_array['message'], 400);
            }

            
            /*=======================================================
             * 下车写入日志 end
             * ======================================================
             */

            /*=======================================================
            * 下车保存订单轨迹 start
            * ======================================================
            */

            quanli_include('module/base/bill/billEdit.class.php');

            $operator = $G_PGLOB->currentUserID;
            $content = '您的订单已配送站收货';

            $billEdit = new billEdit( $G_PGLOB->DBCA);
            $billTrace = $billEdit->addBillTrace( $bill_no, $operator, $content );
            if ( !$billTrace ){
                throw new Exception( '订单轨迹保存失败', 400);
            }

            /*=======================================================
             * 下车保存订单轨迹 end
             * ======================================================
             */

            //提交事务
            $G_PGLOB->DBCA->commit();

            returnJsonData( '下车成功', 200 );

        }catch (Exception $e){

            //回滚事务
            $G_PGLOB->DBCA->rollBack();

            if ($e->getCode() > 0) {
                returnJsonData( $e->getMessage(),$e->getCode());
            } else {
                returnJsonData( '系统错误，请与管理员联系',500);
            }
        }

    }
    /*
     *  BD双11活动送礼包
     *  @package ajax
     *  @backend  shop
     *  @author   allen.qiang <allen.qiang@fistforward.com>
     *  20141105 add by allen.qiang FUN-AC-0013-销售BD双11活动
     *  $reust 订单提交数组
     */
    private function  activities($reust){

        global $G_PGLOB;
        //载入活动类
        quanli_require('module/base/activity/activitySpike.class.php');
        //实例化活动类
        $activityspike=new activitySpike();
        //促销渠道字符串
        $promotion_string=$activityspike->paymentID_11_man.','.$activityspike->paymentID_11_women.','.$activityspike->paymentID_11_pet;
        //查询出此笔订单中符合活动条件的数据
        $promotion_sql="SELECT bill_no,bill_goods_no,promotionID FROM  bill_promotion_log where bill_no=? and promotionID =?";
        $promotion_query=$G_PGLOB->DBCA->stmt_query($promotion_sql,'ss',$reust['data']['bill_no'],$activityspike->selector_goods);

        //查询会员ID d订单编号
        $bill_master_sql="SELECT pcustID,bill_code,billPromotion FROM  bill_master where bill_no=?";
        $bill_master_query=$G_PGLOB->DBCA->stmt_query($bill_master_sql,'s',$reust['data']['bill_no']);
        //查询订单第一条内部备注
        $bill_remark_sql="select  *  from bill_remark where bill_no=? order by createTime asc  LIMIT 1";
        $bill_remark_query=$G_PGLOB->DBCA->stmt_query($bill_remark_sql,'s',$reust['data']['bill_no']);
        $remarkArray=explode('-',$bill_remark_query[0]->remark);

            foreach ($promotion_query as $promotion_obj){
                //插入活动拓展表数据
                $activities_extend=new entity("activities_extend");
                $activities_extend->activityNumber=11000;                                           //活动编号
                $activities_extend->classifyID=11002;                                               //分类ID
                $activities_extend->extend_1=$bill_master_query[0]->bill_code;                     //订单编号
                $activities_extend->extend_4=$remarkArray[0];                                        //礼包信息姓名
                $activities_extend->extend_5=$remarkArray[1];                                        //礼包信息手机
                $activities_extend->extend_6=$bill_master_query[0]->billPromotion;                    //礼包类型ID
                $activities_extend->extend_7=$promotion_obj->promotionID;                           //促销渠道ID
                $activities_extend->extend_8=$bill_master_query[0]->pcustID;                       //会员ID
                $activities_extend->extend_9=$promotion_obj->bill_goods_no;                       //订单商品流水号
                $G_PGLOB->DBCA->save($activities_extend);
            }


    }

}
